package com.example.jussi.filestoreddemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    EditText editText;
    String fileName = "jussi.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView2);
        editText = (EditText) findViewById(R.id.editText);
    }

    public void save(View hhView) throws FileNotFoundException {
        if("".equals(editText.getText().toString())){
            Toast.makeText(this, "Please input ...", Toast.LENGTH_SHORT).show();
            return;
        }
        FileOutputStream fileOutputStream = openFileOutput(fileName, MODE_APPEND);
        PrintStream printStream = new PrintStream(fileOutputStream);
        printStream.println(editText.getText().toString());
    }

    public void read(View hhView) throws IOException {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = openFileInput(fileName);
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "This file not found ...", Toast.LENGTH_SHORT).show();
            return;
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
        String tempString;
        textView.setText("文件路径为：" + MainActivity.this.getFilesDir() + "\n");
        while((tempString = bufferedReader.readLine()) != null){
            textView.append(tempString + "\n");
        };
    }
}
